<template>
	<view class="content">
		<view class="bg-box">
			<image class="bg-img" src="/static/index/bg.png" mode=""></image>
		</view>
		<z-paging class="contBox" ref="paging" v-model="dataList" @query="queryList">
			<view slot="top">
				<u-navbar placeholder  title="购物车" :autoBack="true" >
					
					<view class="navbar-title" slot="right">
						<u-icon @click="deleteSelected" class="iconclass" name="trash" color="#000" size="26"></u-icon>
					</view>
				</u-navbar>
				<view style="height: 52rpx;"></view>
			</view>
			<view class="shopBox" v-if="dataList.length">
				<u-checkbox-group placement="column" v-model="selectidlist">
					<view class="spli" v-for="(item,index) in dataList" :key="item.id">
						<view class="spdiv">
							<view style="display: flex;">
								<u-checkbox v-model="item.checked" :name="item.id" shape="circle" iconColor="#000"
									iconSize="16" activeColor="#DB0000" size="24"
									style="padding-right: 15rpx;"></u-checkbox>
								<view class="imgdiv">
									<image :src="item.productImg" mode="" style="border-radius: 10rpx;"></image>
								</view>
								<view class="sptxts">
									<view class="sptxt">{{item.productName}}</view>
									<view class="specul">
										<view class="specli">
											{{parseSpec(item.productSpec && item.productSpec.specJson)}}
											<!-- <u-icon class="iconclass" name="arrow-right" color="#636363" size="10"></u-icon> -->
										</view>
									</view>
									<view class="muchBox flexbt">
										<view class="product-price">
											<!-- 会员价格显示 -->
											<view v-if="Userinfo.vip && item.vipPrice" class="vip-price-container">
												<view class="vip-price">
													<text class="price-symbol vip-symbol">¥</text>
													<text class="price-amount vip-amount">{{item.vipPrice}}</text>
												</view>
												<view class="original-price">
													<text class="price-symbol">¥</text>
													<text class="price-amount original-amount">{{item.productPrice}}</text>
												</view>
											</view>
											<!-- 非会员价格显示 -->
											<view v-else class="normal-price">
												<text class="price-symbol">¥</text>
												<text class="price-amount">{{item.productPrice}}</text>
											</view>
										</view>
										<u-number-box v-model="item.count" @change="valChangeCart(item, $event)">
											<view slot="minus" class="minus">
												<u-icon name="minus" color="#000" size="12"></u-icon>
											</view>
											<text slot="input" class="input">{{item.count}}</text>
											<view slot="plus" class="plus">
												<u-icon name="plus" color="#000" size="12"></u-icon>
											</view>
										</u-number-box>
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<view slot="bottom">
				<view class="flexbt btmBox">
					<view class="flexstart">
						<u-checkbox :checked="isAllChecked" @change="checkboxChange" iconColor="#000" iconSize="16"
							shape="circle" activeColor="#DB0000" size="24" style="padding-right: 15rpx;"></u-checkbox>
						<view>全选 合计:¥ {{totalPrice}}</view>
					</view>
					<view class="btnBox" @click="toOrder">结算</view>
				</view>
			</view>
		</z-paging>
	</view>
</template>

<script>
	import { getCartList, updateCartItem, deleteCartItem, deleteCartItems, createCartOrder } from '@/api/mall.js'
	import store from '@/store/index.js'
	
	export default {
		data() {
			return {
				dataList: [], //
				navOpacity: 0,
				imglist: [{
						img: '/static/index/21.png',
						txt: '每日签到'
					},
					{
						img: '/static/index/21.png',
						txt: '排行榜'
					},
					{
						img: '/static/index/21.png',
						txt: '分享'
					},
					{
						img: '/static/index/21.png',
						txt: '商学院'
					},
					{
						img: '/static/index/21.png',
						txt: '商学院'
					}
				],
				tabindex: 0,
				numvalue: 1, //数量
				selectidlist: [], // 选中的id	
				totalPrice: 0,
				isAllChecked: false,
			}
		},
		watch: {
			selectidlist: {
				handler(val) {
					this.calcTotal();
					this.updateAllChecked();
				},
				immediate: true
			},
			dataList: {
				handler(val) {
					this.updateAllChecked();
				},
				immediate: true
			}
		},
		computed: {
			Userinfo() {
				return this.$store.state.userinfo;
			}
		},
		onShow() {
			// 确保paging组件已经初始化
			if (this.$refs.paging) {
				this.$refs.paging.reload();
			}
			this.$store.commit('setCoupon', '');
			this.$store.commit('setAddress', '');
		},
		methods: {
			calcTotal() {
				let total = 0;
				this.dataList.forEach(item => {
					if (this.selectidlist.includes(item.id)) {
						// 如果是VIP用户且有VIP价格，使用VIP价格；否则使用原价
						const price = (this.Userinfo.vip && item.vipPrice) ? parseFloat(item.vipPrice) : parseFloat(item.productPrice);
						total += price * Number(item.count);
					}
				});
				this.totalPrice = total.toFixed(2);
			},
			queryList(pageNo, pageSize) {
				// 调用API获取购物车数据
				const userId = store.state.userid
				if (userId) {
					getCartList({
						userId: userId,
						pageNo: pageNo,
						pageSize: pageSize
					}).then(res => {
						if (res.code == 200) {
							// 根据实际API返回的数据结构处理
							const cartData = res.data || []
							// 为每个商品添加checked属性
							const processedData = cartData.map(item => ({
								...item,
								checked: false
							}))
							this.$refs.paging.complete(processedData)
						} else {
							this.$refs.paging.complete([])
						}
					}).catch(err => {
						console.error('获取购物车失败:', err)
						this.$refs.paging.complete([])
					})
				} else {
					this.$refs.paging.complete([])
				}
			},
			
			// 使用假数据（备用）
			getMockData() {
				const mockData = [
					{
						id: 1,
						productId: 101,
						productName: '本店招牌葱烧鱼 - 新鲜美味，口感绝佳',
						productImg: '/static/index/test2.jpg',
						productPrice: '29.8',
						vipPrice: '25.8', // 添加VIP价格
						needPoint: 100,
						count: 2,
						checked: false,
						productSpec: {
							specJson: '{"规格":"大份","口味":"微辣"}'
						}
					},
					{
						id: 2,
						productId: 102,
						productName: '招牌红烧肉 - 肥而不腻，入口即化',
						productImg: '/static/index/test2.jpg',
						productPrice: '35.8',
						vipPrice: '32.8', // 添加VIP价格
						needPoint: 120,
						count: 1,
						checked: false,
						productSpec: {
							specJson: '{"规格":"中份","口味":"不辣"}'
						}
					},
					{
						id: 3,
						productId: 103,
						productName: '清蒸鲈鱼 - 鲜嫩爽滑，营养丰富',
						productImg: '/static/index/test2.jpg',
						productPrice: '42.8',
						vipPrice: '38.8', // 添加VIP价格
						needPoint: 150,
						count: 1,
						checked: false,
						productSpec: {
							specJson: '{"规格":"大份","口味":"清淡"}'
						}
					},
					{
						id: 4,
						productId: 104,
						productName: '宫保鸡丁 - 麻辣鲜香，下饭神器',
						productImg: '/static/index/test2.jpg',
						productPrice: '28.8',
						vipPrice: '24.8', // 添加VIP价格
						needPoint: 80,
						count: 3,
						checked: false,
						productSpec: {
							specJson: '{"规格":"小份","口味":"中辣"}'
						}
					},
					{
						id: 5,
						productId: 105,
						productName: '麻婆豆腐 - 嫩滑爽口，麻辣过瘾',
						productImg: '/static/index/test2.jpg',
						productPrice: '18.8',
						vipPrice: '16.8', // 添加VIP价格
						needPoint: 60,
						count: 2,
						checked: false,
						productSpec: {
							specJson: '{"规格":"中份","口味":"重辣"}'
						}
					}
				];
				
				// 模拟异步加载
				setTimeout(() => {
					this.$refs.paging.complete(mockData);
				}, 500);
			},
			changtab(index) {
				this.tabindex = index
			},
			// 搜索
			tosearch() {
				uni.navigateTo({
					url: '/pagesA/search/search'
				})
			},
			valChange(e) {
				console.log('当前值为: ' + e.value)
			},

			// 选中id集合this.selectidlist
			checkboxChange(e) {
				if (e) {
					this.checkedAll()
				} else {
					return this.selectidlist = []
				}
			},
			// 全选
			checkedAll() {
				this.$nextTick(() => {
					this.selectidlist = []
					this.dataList.map(item => {
						this.selectidlist.push(item.id)
					})
				})

			},
			onPageScrolls(e) {
				const scrollTop = e;
				const maxScrollTop = 50; // 最大滚动距离
				const opacity = scrollTop / maxScrollTop;
				this.navOpacity = opacity > 1 ? 1 : opacity;
			},
			updateAllChecked() {
				if (!this.dataList.length) {
					this.isAllChecked = false;
					return;
				}
				this.isAllChecked = this.dataList.every(item => this.selectidlist.includes(item.id));
			},
			valChangeCart(item, e) {
				const newCount = e.value;
				if (newCount < 1) return;
				
				// 调用API更新购物车数量
				updateCartItem({
					cartId: item.id,
					quantity: newCount
				}).then(res => {
					if (res.code == 200) {
						item.count = newCount;
						uni.showToast({
							title: '数量已更新',
							icon: 'success'
						});
						this.calcTotal(); // 数量变更后实时更新合计
					} else {
						uni.showToast({
							title: res.msg || '更新失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('更新购物车失败:', err)
					uni.showToast({
						title: '更新失败，请重试',
						icon: 'none'
					});
				});
			},
			parseSpec(specJson) {
				if (!specJson) return '';
				try {
					const obj = JSON.parse(specJson);
					return Object.keys(obj).map(k => `${k}:${obj[k]}`).join(' ');
				} catch (e) {
					return specJson;
				}
			},
			deleteSelected() {
				if (!this.selectidlist.length) {
					uni.showToast({
						title: '请选择要删除的商品',
						icon: 'none'
					});
					return;
				}
				
				// 显示确认删除弹窗
				uni.showModal({
					title: '确认删除',
					content: `确定要删除选中的 ${this.selectidlist.length} 个商品吗？`,
					success: (res) => {
						if (res.confirm) {
							this.performDelete();
						}
					}
				});
			},
			
			// 执行删除操作
			performDelete() {
				uni.showLoading({
					title: '删除中...'
				});
				
				// 使用批量删除API
				deleteCartItems(this.selectidlist).then(res => {
					uni.hideLoading();
					
					if (res.code == 200) {
						// 删除成功，更新本地数据
						this.dataList = this.dataList.filter(item => !this.selectidlist.includes(item.id));
						this.selectidlist = [];
						
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						
						this.calcTotal();
					} else {
						uni.showToast({
							title: res.message || '删除失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('删除购物车商品失败:', err);
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
				});
			},
			toOrder() {
				const selected = this.dataList.filter(item => this.selectidlist.includes(item.id));
				if (!selected.length) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					});
					return;
				}
				
				// 提取购物车ID列表
				const cartIds = selected.map(item => item.id);
				
				// 将选中的商品信息和购物车ID编码为JSON字符串通过URL参数传递
				const productData = encodeURIComponent(JSON.stringify(selected));
				const cartIdsData = encodeURIComponent(JSON.stringify(cartIds));
				
				// 跳转到结算页面，通过URL参数传递商品数据和购物车ID
				uni.navigateTo({
					url: `/pagesB/submitorder/submitorder?type=cart&products=${productData}&cartIds=${cartIdsData}`
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.minus {
		width: 46rpx;
		height: 46rpx;
		color: #fff;
		border-width: 2rpx;
		border-color: #666666;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 0;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 0;
		@include flex;
		justify-content: center;
		align-items: center;
	}

	.input {
		color: #000;
		width: 46rpx;
		height: 46rpx;
		line-height: 46rpx;
		border-width: 2rpx;
		border-color: #666666;
		border-style: solid;
		text-align: center;
	}

	.plus {
		width: 46rpx;
		height: 46rpx;
		color: #fff;
		border-width: 2rpx;
		border-color: #666666;
		border-style: solid;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 0;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.content {
		.bg-box {
			height: 100vh;
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;

			.bg-img {
				width: 100%;
				height: 100vh;
			}
		}

		.gwctitle {
			font-size: 44rpx;
			color: #333333;
			font-weight: 600;
		}

		.shopBox {
			margin: 0 24rpx;
			padding: 40rpx 26rpx;
			background-color: #F6F7F9;
			border-radius: 32rpx 32rpx 16rpx 16rpx;

			.u-checkbox::v-deep {
				align-items: flex-start;
				margin-top: 70rpx;
			}

			.spli {
				margin-bottom: 32rpx;

				.spnameBox {
					font-weight: 600;
					font-size: 30rpx;
					color: #333333;
					padding: 22rpx 0 32rpx;

					image {
						width: 36rpx;
						height: 36rpx;
						margin-right: 20rpx;

					}
				}

				.spdiv {
					margin-bottom: 22rpx;



					.xuanze {}

					.imgdiv {
						width: 164rpx;
						height: 164rpx;
						margin-right: 20rpx;

						image {
							width: 164rpx;
							height: 164rpx;
						}
					}

					.sptxts {
						flex: 1;

						.sptxt {
							opacity: 1;
							color: #1C234C;
							font-size: 36rpx;
							font-weight: 700;
							font-family: "PingFang";
							text-align: left;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
						}

						.specul {
							margin: 16rpx 0 42rpx;

							.specli {
								width: fit-content;
								font-size: 22rpx;
								color: #777B94;
								padding: 6rpx 20rpx;
								background: rgba(0, 0, 0, 0.05);
								border-radius: 50rpx;
								margin-bottom: 10rpx;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 1;
								overflow: hidden;

								.iconclass {
									display: inline-block;
									margin-left: 10rpx;
								}
							}

						}

						.muchBox {
							width: 100%;
							font-family: PingFangSC, PingFang SC;
							font-weight: 600;
							font-size: 24rpx;
							color: #FF2F00;
							margin-top: 16rpx;

							.product-price {
								display: flex;
								align-items: baseline;
								
								.vip-price-container {
									display: flex;
									flex-direction: column;
									align-items: flex-start;
									
									.vip-price {
										display: flex;
										align-items: baseline;
										margin-bottom: 4rpx;
										
										.vip-symbol {
											font-size: 28rpx;
											color: #FF6B35;
											line-height: 1em;
										}
										
										.vip-amount {
											font-size: 40rpx;
											color: #FF6B35;
											line-height: 1em;
											font-weight: 600;
										}
									}
									
									.original-price {
										display: flex;
										align-items: baseline;
										
										.price-symbol {
											font-size: 24rpx;
											color: #999999;
											line-height: 1em;
										}
										
										.original-amount {
											font-size: 28rpx;
											color: #999999;
											line-height: 1em;
											font-weight: 400;
											text-decoration: line-through;
										}
									}
								}
								
								.normal-price {
									display: flex;
									align-items: baseline;
									
									.price-symbol {
										font-size: 28rpx;
										color: #FF2F00;
										line-height: 1em;
									}
									
									.price-amount {
										font-size: 40rpx;
										color: #FF2F00;
										line-height: 1em;
										font-weight: 600;
									}
								}
							}

							.muchtxt {
								font-size: 36rpx;
								color: #FF2F00;
								margin-right: 10rpx;
							}

							.numtxt {
								font-size: 28rpx;
								color: #999999;
							}

							image {
								width: 56rpx;
								height: 56rpx;
								border-radius: 100%;
							}
						}
					}


				}
			}
		}

		.btmBox {
			padding: 34rpx 24rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #1C234C;

			.btnBox {
				width: 220rpx;
				height: 72rpx;
				border-radius: 50rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #FFFFFF;
				line-height: 72rpx;
				text-align: center;
				background-color: #DB0000;
			}
		}
	}
</style>